<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是通信协议——SPI通信相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="通信协议-04-SPI通信">
<meta property="og:url" content="https://sumumm.github.io/post/649464bc.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是通信协议——SPI通信相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20220923064422211.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20220923065836425.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20230502091928859.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI003.jpg">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI004.jpeg">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI005.jpeg">
<meta property="article:published_time" content="2022-09-21T09:31:13.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.061Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="通信协议">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20220923064422211.png">


<link rel="canonical" href="https://sumumm.github.io/post/649464bc.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/649464bc.html","path":"post/649464bc.html","title":"通信协议-04-SPI通信"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>通信协议-04-SPI通信 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81-SPI%E5%8D%8F%E8%AE%AE%E7%AE%80%E4%BB%8B"><span class="nav-text">一、 SPI协议简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFSPI%EF%BC%9F"><span class="nav-text">1. 什么是SPI？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%B8%8EI2C%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="nav-text">2. 与I2C的对比</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E7%AE%80%E4%BB%8B"><span class="nav-text">二、基本原理简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E8%AE%BE%E5%A4%87%E8%BF%9E%E6%8E%A5"><span class="nav-text">三、设备连接</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%89%A9%E7%90%86%E6%8B%93%E6%89%91%E7%BB%93%E6%9E%84"><span class="nav-text">1. 物理拓扑结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%95%B0%E6%8D%AE%E4%BA%A4%E6%8D%A2"><span class="nav-text">2. 数据交换</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81SPI%E9%80%9A%E4%BF%A1%E8%BF%87%E7%A8%8B"><span class="nav-text">四、SPI通信过程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E9%80%9A%E4%BF%A1%E6%97%B6%E5%BA%8F"><span class="nav-text">1. 通信时序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%B5%B7%E5%A7%8B%E4%B8%8E%E5%81%9C%E6%AD%A2%E4%BF%A1%E5%8F%B7"><span class="nav-text">2. 起始与停止信号</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E6%95%B0%E6%8D%AE%E4%BC%A0%E8%BE%93"><span class="nav-text">3. 数据传输</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%9B%9B%E7%A7%8D%E9%80%9A%E4%BF%A1%E6%A8%A1%E5%BC%8F"><span class="nav-text">4.四种通信模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-CPOL%E4%B8%8ECPHA"><span class="nav-text">4.1 CPOL与CPHA</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-CPHA-0"><span class="nav-text">4.2 CPHA &#x3D; 0</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-CPHA-1"><span class="nav-text">4.3 CPHA &#x3D; 1</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E6%A8%A1%E6%8B%9FSPI"><span class="nav-text">五、模拟SPI</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-GPIO%E9%80%89%E6%8B%A9%E4%B8%8E%E5%BC%95%E8%84%9A%E5%AE%9A%E4%B9%89"><span class="nav-text">1. GPIO选择与引脚定义</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%AE%8F%E5%AE%9A%E4%B9%89"><span class="nav-text">1.1 宏定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-GPIO%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="nav-text">1.2 GPIO初始化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BB%B6%E6%97%B6%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89"><span class="nav-text">2. 延时函数定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-SPI%E8%AF%BB%E5%86%99%E5%87%BD%E6%95%B0"><span class="nav-text">3. SPI读写函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-%E5%86%99%E4%B8%80%E4%B8%AA%E5%AD%97%E8%8A%82"><span class="nav-text">3.1 写一个字节</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-%E8%AF%BB%E4%B8%80%E4%B8%AA%E5%AD%97%E8%8A%82"><span class="nav-text">3.2 读一个字节</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-%E8%AF%BB%E5%86%99%E4%B8%80%E4%B8%AA%E5%AD%97%E8%8A%82"><span class="nav-text">3.3 读写一个字节</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/649464bc.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="通信协议-04-SPI通信 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          通信协议-04-SPI通信
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-09-21 17:31:13" itemprop="dateCreated datePublished" datetime="2022-09-21T17:31:13+08:00">2022-09-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/" itemprop="url" rel="index"><span itemprop="name">03通信协议</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.2k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>19 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是通信协议——SPI通信相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">驱动开发指南</td><td align="left"><a href="http://47.111.11.73/docs/boards/arm-linux/zdyz-i.mx6ull.html#i-mx6ull-linux" target="_blank">i.MX6ULL Linux阿尔法开发板资料 <i class="fa fa-external-link-alt"></i> </a></td></tr>    <tr><td align="left">STM32开发指南</td><td align="left"><a href="http://www.openedv.com/docs/boards/stm32/zdyz_stm32f103_warship.html#id3" target="_blank">STM32F1开发指南-库函数版本_V3.3 <i class="fa fa-external-link-alt"></i> </a></td></tr>    <tr><td align="left">野火STM32开发指南</td><td align="left"><a href="https://doc.embedfire.com/mcu/stm32/f103badao/std/zh/latest/book/communication.html" target="_blank">STM32库开发实战指南——基于野火霸道开发板 文档 (embedfire.com) <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">---</td>        <td align="left">--- <a href="" target="_blank">  <i class="fa fa-external-link-alt"></i></a></td>      </tr></table>
              </div>
            </details>

<h1 id="一、-SPI协议简介"><a href="#一、-SPI协议简介" class="headerlink" title="一、 SPI协议简介"></a><font size=3>一、 SPI协议简介</font></h1><h2 id="1-什么是SPI？"><a href="#1-什么是SPI？" class="headerlink" title="1. 什么是SPI？"></a><font size=3>1. 什么是SPI？</font></h2><p>SPI 协议，Serial Peripheral Interface  ，即串行外围设备接口， 是由摩托罗拉公司提出的通讯协议（ Motorola） 在1980前后提出的一种全双工同步串行通信接口，它用于MCU与各种外围设备以串行方式进行通信以交换信息，通信速度最高可达25MHz以上。SPI接口主要应用在EEPROM、 FLASH、实时时钟、网络控制器、 OLED显示驱动器、 AD转换器，数字信号处理器、数字信号解码器等与MCU间要求通讯速率较高的场合 。</p>
<p>SPI，是一种<strong>高速</strong>的，<strong>全双工</strong>，<strong>同步</strong>的通信总线，并且在芯片的管脚上只占用四根线，节约了芯片的管脚，同时为PCB的布局上节省空间，提供方便，主要应用在 EEPROM，FLASH，实时时钟，AD转换器，还有数字信号处理器和数字信号解码器之间。</p>
<p>SPI 时钟频率相比 I2C 要高很多，最高可以工作在上百 MHz。 SPI 以主从方式工作，通常是有一个主设备和一个或多个从设备，一般 SPI 需要 4 根线，但是也可以使用三根线(单向传输) 。</p>
<h2 id="2-与I2C的对比"><a href="#2-与I2C的对比" class="headerlink" title="2. 与I2C的对比"></a><font size=3>2. 与I2C的对比</font></h2><table>
<thead>
<tr>
<th>功能说明</th>
<th>SPI总线</th>
<th>I2C总线</th>
</tr>
</thead>
<tbody><tr>
<td>通信方式</td>
<td>同步 串行 全双工</td>
<td>同步 串行 半双工</td>
</tr>
<tr>
<td>通信速度</td>
<td>一般50MHz以下</td>
<td>100KHz、 400KHz、 3.4MHz</td>
</tr>
<tr>
<td>从设备选择</td>
<td>引脚片选</td>
<td>设备地址片选</td>
</tr>
<tr>
<td>总线接口</td>
<td>MOSI、 MISO、 SCK、 CS</td>
<td>SDA、 SCL</td>
</tr>
</tbody></table>
<p>SPI通常由四条线组成，一条主设备输出与从设备输入（ Master Output Slave Input， MOSI） ， 一条主设备输入与从设备输出（ Master Input Slave Output， MISO） ， 一条时钟信号（ Serial Clock， SCLK） ，一条从设备使能选择（ Chip Select， CS） 。 与I2C类似，协议都比较简单，也可以使用GPIO模拟SPI时序。</p>
<p>SPI可以同时发出和接收数据，因此SPI的理论传输速度比I2C更快。 SPI通过片选引脚选择从机，一个片选一个从机，因此在多从机结构中，需要占用较多引脚，而I2C通过设备地址选择从机，只要设备地址不冲突，始终只需要两个引脚。  </p>
<h1 id="二、基本原理简介"><a href="#二、基本原理简介" class="headerlink" title="二、基本原理简介"></a><font size=3>二、基本原理简介</font></h1><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20220923064422211.png" alt="image-20220923064422211" style="zoom:50%;" />

<ul>
<li>（1）SPI接口一般使用 4 条线通信：</li>
</ul>
<table>
<thead>
<tr>
<th>接口名称</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>MISO</td>
<td>主设备数据输入，从设备数据输出</td>
</tr>
<tr>
<td>MOSI</td>
<td>主设备数据输出，从设备数据输入</td>
</tr>
<tr>
<td>SCLK</td>
<td>时钟信号，由主设备产生</td>
</tr>
<tr>
<td>CS</td>
<td>从设备片选信号，由主设备控制</td>
</tr>
</tbody></table>
<ul>
<li>（2）主机和从机都有一个串行移位寄存器，主机通过向它的SPI串行寄存器写入一个字节来发起一次传输。</li>
<li>（3）串行移位寄存器通过MOSI信号线将字节传送给从机，从机也将自己的串行移位寄存器中的内容通过MISO信号线返回给主机。这样，两个移位寄存器中的内容就被交换。</li>
<li>（4）外设的写操作和读操作是同步完成的。如果只进行写操作，主机只需忽略接收到的字节；反之，若主机要读取从机的一个字节，就必须发送一个空字节来引发从机的传输。</li>
</ul>
<h1 id="三、设备连接"><a href="#三、设备连接" class="headerlink" title="三、设备连接"></a><font size=3>三、设备连接</font></h1><h2 id="1-物理拓扑结构"><a href="#1-物理拓扑结构" class="headerlink" title="1. 物理拓扑结构"></a><font size=3>1. 物理拓扑结构</font></h2><p>SPI通信设备之间常见的连接方式如下图：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20220923065836425.png" alt="image-20220923065836425" style="zoom:50%;" />

<ul>
<li>CS( Slave Select)：从设备选择信号线，常称为片选信号线，也称为NSS、CS，以下用CS表示。</li>
</ul>
<p>当有多个SPI从设备与SPI主机相连时， 设备的其它信号线SCK、MOSI及MISO同时并联到相同的SPI总线上，即无论有多少个从设备，都共同只使用这3条总线； 而每个从设备都有独立的这一条CS信号线，本信号线独占主机的一个引脚，即有多少个从设备，就有多少条片选信号线。</p>
<p>I2C协议中通过设备地址来寻址、选中总线上的某个设备并与其进行通讯；而SPI协议中没有设备地址，它<strong>使用CS信号线来寻址</strong>， 当主机要选择从设备时，把该从设备的NSS信号线设置为低电平，该从设备即被选中，即片选有效， 接着主机开始与被选中的从设备进行SPI通讯。所以SPI通讯以CS线置低电平为开始信号，以CS线被拉高作为结束信号。</p>
<ul>
<li>SCK (Serial Clock)：时钟信号线，用于通讯数据同步</li>
</ul>
<p>它由通讯主机产生，决定了通讯的速率，不同的设备支持的最高时钟频率不一样， 如STM32的SPI时钟频率最大为 fpclk&#x2F;2 ，两个设备之间通讯时，通讯速率受限于低速设备。</p>
<ul>
<li>MOSI (Master Output， Slave Input)：主设备输出&#x2F;从设备输入引脚。</li>
</ul>
<p>主机的数据从这条信号线输出， 从机由这条信号线读入主机发送的数据，即这条线上数据的方向为主机到从机。</p>
<ul>
<li>MISO(Master Input,，Slave Output)：主设备输入&#x2F;从设备输出引脚。</li>
</ul>
<p>主机从这条信号线读入数据， 从机的数据由这条信号线输出到主机，即在这条线上数据的方向为从机到主机。</p>
<h2 id="2-数据交换"><a href="#2-数据交换" class="headerlink" title="2. 数据交换"></a><font size=3>2. 数据交换</font></h2><p>在SCK时钟周期的驱动下， MOSI和MISO同时进行，如下图所示，可以看作一个虚拟的环形拓扑结构。 </p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/image-20230502091928859.png" alt="image-20230502091928859" style="zoom:33%;" />

<p>主机和从机都有一个移位寄存器，主机移位寄存器数据经过MOSI将数据写入从机的移位寄存器，此时从机移位寄存器的数据也通过MISO传给了主机，实现了两个移位寄存器的数据交换。无论主机还是从机，发送和接收都是同时进行的，如同一个“环”。如果主机只对从机进行写操作，主机只需忽略接收的从机数据即可。如果主机要读取从机数据，需要主机发送一个空数据来引发从机发送数据。  </p>
<h1 id="四、SPI通信过程"><a href="#四、SPI通信过程" class="headerlink" title="四、SPI通信过程"></a><font size=3>四、SPI通信过程</font></h1><h2 id="1-通信时序"><a href="#1-通信时序" class="headerlink" title="1. 通信时序"></a><font size=3>1. 通信时序</font></h2><p>这里的片选引脚用 NSS 表示了，它与CS是一个意思，前边有说明。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI003.jpg" alt="SPI通讯时序" style="zoom:50%;" />

<p>这是一个主机的通讯时序。NSS、SCK、MOSI信号都由主机控制产生，而MISO的信号由从机产生，主机通过该信号线读取从机的数据。 MOSI与MISO的信号只在NSS为低电平的时候才有效，在SCK的每个时钟周期MOSI和MISO传输一位数据。SPI通信<strong>发送是先发高字节再发低字节，接收是先收高字节再收低字节</strong>。</p>
<h2 id="2-起始与停止信号"><a href="#2-起始与停止信号" class="headerlink" title="2. 起始与停止信号"></a><font size=3>2. 起始与停止信号</font></h2><p>SPI通信协议图中标号为 ① 和  ⑥ 的地方为起始和停止信号：</p>
<ul>
<li><p><strong>NSS信号线由高变低</strong>，是SPI通讯的起始信号。NSS是每个从机各自独占的信号线， 当从机在自己的NSS线检测到起始信号后，就知道自己被主机选中了，开始准备与主机通讯。</p>
</li>
<li><p><strong>NSS信号由低变高</strong>， 是SPI通讯的停止信号，表示本次通讯结束，从机的选中状态被取消。</p>
</li>
</ul>
<h2 id="3-数据传输"><a href="#3-数据传输" class="headerlink" title="3. 数据传输"></a><font size=3>3. 数据传输</font></h2><p>SPI使用MOSI及MISO信号线来传输数据，使用SCK信号线进行数据同步。MOSI及MISO数据线在SCK的<strong>每个时钟周期传输一位数据</strong>， 且数据<strong>输入输出是同时进行</strong>的。数据传输时，MSB先行或LSB先行并没有作硬性规定，但要保证两个SPI通讯设备之间使用同样的协定， 一般都会采用图 SPI通讯时序中的MSB先行模式。<strong>SPI每次数据传输可以8位或16位为单位，每次传输的单位数不受限制</strong>。</p>
<p>图中的 ②、③、④、⑤标号处，MOSI及MISO的数据在SCK的上升沿期间变化输出，在SCK的下降沿时被采样。即在SCK的下降沿时刻， MOSI及MISO的数据有效，高电平时表示数据“1”，为低电平时表示数据“0”。在其它时刻，数据无效，MOSI和MISO为下一次传输数据做准备。</p>
<h2 id="4-四种通信模式"><a href="#4-四种通信模式" class="headerlink" title="4.四种通信模式"></a><font size=3>4.四种通信模式</font></h2><h3 id="4-1-CPOL与CPHA"><a href="#4-1-CPOL与CPHA" class="headerlink" title="4.1 CPOL与CPHA"></a><font size=3>4.1 CPOL与CPHA</font></h3><p>SPI 有四种工作模式，通过串行时钟极性(CPOL)和相位(CPHA)的搭配来得到四种工作模式。</p>
<p>CPOL（ Clock Polarity，时钟极性） 表示SCK在空闲时（即SPI通讯开始前、 NSS线为高电平时SCK的状态）为高电平还是低电平。 当CPOL&#x3D;0， SCK空闲时为低电平， 当CPOL&#x3D;1， SCK空闲时为高电平。  </p>
<p>CPHA（ Clock Phase，时钟相位） 表示SCK在第几个时钟边缘采样数据。 当CPHA&#x3D;0， 在SCK第一个边沿采样数据，当CPHA&#x3D;1， 在SCK第二个边沿采样数据。  也可以这样理解，时钟相位CPHA是指数据的采样的时刻，当CPHA&#x3D;0时， MOSI或MISO数据线上的信号将会在SCK时钟线的“奇数边沿”被采样。当CPHA&#x3D;1时，数据线在SCK的“偶数边沿”采样。  这样搭配下来就会有四种模式：</p>
<ul>
<li>CPOL&#x3D;0，串行时钟空闲状态为低电平。</li>
<li>CPOL&#x3D;1，串行时钟空闲状态为高电平，此时可以通过配置时钟相位(CPHA)来选择具体的传输协议。</li>
<li>CPHA&#x3D;0，串行时钟的第一个跳变沿(上升沿或下降沿)采集数据。</li>
<li>CPHA&#x3D;1，串行时钟的第二个跳变沿(上升沿或下降沿)采集数据。</li>
</ul>
<table>
<thead>
<tr>
<th align="center">SPI模式</th>
<th align="center">CPOL</th>
<th align="center">CPHA</th>
<th align="center">空闲时SCK时钟</th>
<th align="center">采样时刻</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">低电平</td>
<td align="center">奇数边沿</td>
<td>时钟空闲状态为低电平； 在时钟第一个边沿（上升沿） 采样数据</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center">0</td>
<td align="center">1</td>
<td align="center">低电平</td>
<td align="center">偶数边沿</td>
<td>时钟空闲状态为低电平； 在时钟第二个边沿（下降沿） 采样数据</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">1</td>
<td align="center">0</td>
<td align="center">高电平</td>
<td align="center">奇数边沿</td>
<td>时钟空闲状态为高电平； 在时钟第一个边沿（下降沿） 采样数据</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">1</td>
<td align="center">1</td>
<td align="center">高电平</td>
<td align="center">偶数边沿</td>
<td>时钟空闲状态为高电平； 在时钟第二个边沿（上升沿） 采样数据</td>
</tr>
</tbody></table>
<p>实际使用较多的是模式0和模式3。</p>
<h3 id="4-2-CPHA-0"><a href="#4-2-CPHA-0" class="headerlink" title="4.2 CPHA &#x3D; 0"></a><font size=3>4.2 CPHA &#x3D; 0</font></h3><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI004.jpeg" alt="CPHA=0时的SPI通讯模式" style="zoom:50%;" />

<p>这是 CPHA&#x3D;0 的时序图：</p>
<p>（1）首先，根据SCK在空闲状态时的电平，分为两种情况。 SCK信号线在空闲状态为低电平时，CPOL&#x3D;0；空闲状态为高电平时，CPOL&#x3D;1。</p>
<p>（2）无论CPOL&#x3D;0还是1，由于我们配置的时钟相位CPHA&#x3D;0，采样时刻都是在SCK的奇数边沿。 注意当CPOL&#x3D;0的时候，时钟的奇数边沿是上升沿，而CPOL&#x3D;1的时候，时钟的奇数边沿是下降沿，所以SPI的采样时刻不是由上升&#x2F;下降沿决定的。 MOSI和MISO数据线的有效信号在SCK的奇数边沿保持不变，数据信号将在<strong>SCK奇数边沿时被采样</strong>，在非采样时刻，MOSI和MISO的有效信号才发生切换。</p>
<h3 id="4-3-CPHA-1"><a href="#4-3-CPHA-1" class="headerlink" title="4.3 CPHA &#x3D; 1"></a><font size=3>4.3 CPHA &#x3D; 1</font></h3><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/03%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE-04-SPI%E9%80%9A%E4%BF%A1/img/SPI005.jpeg" alt="CPHA=1时的SPI通讯模式" style="zoom:50%;" />

<p>（1）SCK信号线在空闲状态为低电平时， CPOL&#x3D;0；空闲状态为高电平时， CPOL&#x3D;1。  </p>
<p>（2）与CPHA&#x3D;0类似，当CPHA&#x3D;1时，不受CPOL的影响，数据信号在<strong>SCK的偶数边沿被采样</strong>。MOSI和MISO数据线的有效信号在SCK的偶数边沿保持不变，数据信<br>号将在SC<strong>K偶数边沿时被采样</strong>，在非采样时刻， MOSI和MISO的有效信号才发生切换。  </p>
<h1 id="五、模拟SPI"><a href="#五、模拟SPI" class="headerlink" title="五、模拟SPI"></a><font size=3>五、模拟SPI</font></h1><p>我们已经了解了SPI的通信协议，那么我们接下来来了解一下如何用软件模拟SPI协议，以加深对SPI协议的理解。这里通过STM32驱动W25QXX为例，做基础的初始化和定义（基于HAL库），不过这里只实现SPI并不做对W25QXX读写的说明。</p>
<h2 id="1-GPIO选择与引脚定义"><a href="#1-GPIO选择与引脚定义" class="headerlink" title="1. GPIO选择与引脚定义"></a><font size=3>1. GPIO选择与引脚定义</font></h2><h3 id="1-1-宏定义"><a href="#1-1-宏定义" class="headerlink" title="1.1 宏定义"></a><font size=3>1.1 宏定义</font></h3><p>首先定义SPI传输涉及的四个引脚PA4、 PA5、 PA6、 PA7， 其中MISO（ PA6）为输入引脚，其它全为输出引脚  </p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx                             SPI1</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_CLK_ENABLE()                __HAL_RCC_SPI1_CLK_ENABLE()</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_SCK_GPIO_CLK_ENABLE()       __HAL_RCC_GPIOA_CLK_ENABLE()</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MISO_GPIO_CLK_ENABLE()      __HAL_RCC_GPIOA_CLK_ENABLE() </span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MOSI_GPIO_CLK_ENABLE()      __HAL_RCC_GPIOA_CLK_ENABLE() </span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> W25_CS_GPIO_CLK_ENABLE()         __HAL_RCC_GPIOA_CLK_ENABLE() </span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_FORCE_RESET()               __HAL_RCC_SPI1_FORCE_RESET()</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_RELEASE_RESET()             __HAL_RCC_SPI1_RELEASE_RESET()</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_SCK_PIN                     GPIO_PIN_5</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_SCK_GPIO_PORT               GPIOA</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MISO_PIN                    GPIO_PIN_6</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MISO_GPIO_PORT              GPIOA</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MOSI_PIN                    GPIO_PIN_7</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPIx_MOSI_GPIO_PORT              GPIOA</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> W25_CS_PIN                       GPIO_PIN_4               </span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> W25_CS_GPIO_PORT                 GPIOA    </span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPI_CLK(level)                   HAL_GPIO_WritePin(SPIx_SCK_GPIO_PORT, SPIx_SCK_PIN, level?GPIO_PIN_SET:GPIO_PIN_RESET)                                    </span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPI_MISO()                       HAL_GPIO_ReadPin(SPIx_MISO_GPIO_PORT, SPIx_MISO_PIN)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SPI_MOSI(level)                  HAL_GPIO_WritePin(SPIx_MOSI_GPIO_PORT, SPIx_MOSI_PIN, level?GPIO_PIN_SET:GPIO_PIN_RESET)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> W25_CS(level)                    HAL_GPIO_WritePin(W25_CS_GPIO_PORT, W25_CS_PIN, level?GPIO_PIN_SET:GPIO_PIN_RESET)</span></span><br></pre></td></tr></table></figure>

<h3 id="1-2-GPIO初始化"><a href="#1-2-GPIO初始化" class="headerlink" title="1.2 GPIO初始化"></a><font size=3>1.2 GPIO初始化</font></h3><p>随后将四个GPIO引脚初始化，使能引脚时钟，设置输入&#x2F;输出模式。 SCK、 MOSI、 CS引脚，始终为输出模式， MISO引脚为数据输入引脚， 始终为输入模式</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">SPI_Init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    GPIO_InitTypeDef  GPIO_InitStruct;</span><br><span class="line"></span><br><span class="line">    SPIx_SCK_GPIO_CLK_ENABLE();</span><br><span class="line">    SPIx_MISO_GPIO_CLK_ENABLE();</span><br><span class="line">    SPIx_MOSI_GPIO_CLK_ENABLE();</span><br><span class="line">    W25_CS_GPIO_CLK_ENABLE();</span><br><span class="line">    </span><br><span class="line">    GPIO_InitStruct.Pin       = SPIx_SCK_PIN | W25_CS_PIN | SPIx_MOSI_PIN;</span><br><span class="line">    GPIO_InitStruct.Mode      = GPIO_MODE_OUTPUT_PP;</span><br><span class="line">    GPIO_InitStruct.Pull      = GPIO_PULLUP;</span><br><span class="line">    GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_LOW;</span><br><span class="line">    HAL_GPIO_Init(SPIx_SCK_GPIO_PORT, &amp;GPIO_InitStruct); <span class="comment">// SCK CS MOSI为输出</span></span><br><span class="line">    </span><br><span class="line">    GPIO_InitStruct.Pin       = SPIx_MISO_PIN;</span><br><span class="line">    GPIO_InitStruct.Mode      = GPIO_MODE_INPUT;</span><br><span class="line">    GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_LOW;</span><br><span class="line">    HAL_GPIO_Init(SPIx_MISO_GPIO_PORT, &amp;GPIO_InitStruct); <span class="comment">// MISO为输入</span></span><br><span class="line">    </span><br><span class="line">    W25_CS(<span class="number">1</span>);      <span class="comment">// CS初始化高</span></span><br><span class="line">    SPI_CLK(<span class="number">0</span>);     <span class="comment">// CLK初始化低</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-延时函数定义"><a href="#2-延时函数定义" class="headerlink" title="2. 延时函数定义"></a><font size=3>2. 延时函数定义</font></h2><p>我们既然是模拟SPI，那么就需要手动产生时钟，所以这里当然就需要延时函数啦：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> SPI_Delay()     us_timer_delay(10)</span></span><br></pre></td></tr></table></figure>

<p>定时器实现的延时函数，延时时间为 t us，为了缩短时间，这里这是演示，所以就不写具体实现了，具体的我们可以使用定时器来实现us级延时。</p>
<h2 id="3-SPI读写函数"><a href="#3-SPI读写函数" class="headerlink" title="3. SPI读写函数"></a><font size=3>3. SPI读写函数</font></h2><p>这里假设SPI主机工作在模式0，参考前面的SPI时序。</p>
<h3 id="3-1-写一个字节"><a href="#3-1-写一个字节" class="headerlink" title="3.1 写一个字节"></a><font size=3>3.1 写一个字节</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> *  函数名：void SPI_WriteByte(uint8_t data)</span></span><br><span class="line"><span class="comment"> *  输入参数：data -&gt; 要写的数据</span></span><br><span class="line"><span class="comment"> *  输出参数：无</span></span><br><span class="line"><span class="comment"> *  返回值：无</span></span><br><span class="line"><span class="comment"> *  函数作用：模拟SPI写一个字节</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">SPI_WriteByte</span><span class="params">(<span class="type">uint8_t</span> data)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">uint8_t</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">uint8_t</span> temp = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;<span class="number">8</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        temp = ((data&amp;<span class="number">0x80</span>)==<span class="number">0x80</span>)? <span class="number">1</span>:<span class="number">0</span>; <span class="comment">// 将data最高位保存到temp</span></span><br><span class="line">        data = data&lt;&lt;<span class="number">1</span>;       <span class="comment">// data左移一位，将次高位变为最高位，用于下次取最高位；</span></span><br><span class="line">        </span><br><span class="line">        SPI_CLK(<span class="number">0</span>);           <span class="comment">// 拉低时钟，即空闲时钟为低电平， CPOL=0</span></span><br><span class="line">        SPI_MOSI(temp);       <span class="comment">// 根据temp值，设置MOSI引脚的电平</span></span><br><span class="line">        SPI_Delay();          <span class="comment">// 简单延时，可以定时器或延时函数实现</span></span><br><span class="line">        SPI_CLK(<span class="number">1</span>);           <span class="comment">// 拉高时钟， W25Q64只支持SPI模式0或1，即会在时钟上升沿采样MOSI数据 CPHA=0</span></span><br><span class="line">        SPI_Delay();    </span><br><span class="line">    &#125;</span><br><span class="line">    SPI_CLK(<span class="number">0</span>);              <span class="comment">// 最后SPI发送完后，拉低时钟，进入空闲状态</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 13 - 23 行：SPI写1 Byte，循环8次，每次发送1 Bit。</p>
<h3 id="3-2-读一个字节"><a href="#3-2-读一个字节" class="headerlink" title="3.2 读一个字节"></a><font size=3>3.2 读一个字节</font></h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> *  函数名：uint8_t SPI_ReadByte(void)</span></span><br><span class="line"><span class="comment"> *  输入参数：</span></span><br><span class="line"><span class="comment"> *  输出参数：无</span></span><br><span class="line"><span class="comment"> *  返回值：读到的数据</span></span><br><span class="line"><span class="comment"> *  函数作用：模拟SPI读一个字节</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="type">uint8_t</span> <span class="title function_">SPI_ReadByte</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">uint8_t</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">uint8_t</span> read_data = <span class="number">0xFF</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;<span class="number">8</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        read_data = read_data &lt;&lt; <span class="number">1</span>;  <span class="comment">// “腾空” read_data 最低位， 8次循环后， read_data将高位在前</span></span><br><span class="line">        </span><br><span class="line">        SPI_CLK(<span class="number">0</span>);    <span class="comment">// 拉低时钟，即空闲时钟为低电平；</span></span><br><span class="line">        SPI_Delay();</span><br><span class="line">        SPI_CLK(<span class="number">1</span>);    <span class="comment">// 拉高时钟，此时从设备会发送数据，主机稍微延时一会，再读取MISO电平，得知传入数据</span></span><br><span class="line">        SPI_Delay();</span><br><span class="line">        <span class="keyword">if</span>(SPI_MISO()==<span class="number">1</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            read_data = read_data + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    SPI_CLK(<span class="number">0</span>);       <span class="comment">// 最后SPI读取完后，拉低时钟，进入空闲状态</span></span><br><span class="line">    <span class="keyword">return</span> read_data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 13 - 25 行：SPI读1 Byte，循环8次，每次接收1 Bit。</p>
<h3 id="3-3-读写一个字节"><a href="#3-3-读写一个字节" class="headerlink" title="3.3 读写一个字节"></a><font size=3>3.3 读写一个字节</font></h3><p>SPI传输可以看作一个虚拟的环形拓扑结构，即输入和输出同时进行。在前面“ SPI_WriteByte()”函数里，发送了1 Byte，也应该接收1 Byte，只是代码中忽略了接收引脚MISO的状态； 在前面“ SPI_ReadByte()”函数里，接收了1 Byte，也应该发送1 Byte，只是代码中忽略了发送引脚MOSI的内容。有些场景， SPI需要同时读写，因此还需要编写SPI同时读写函数，  </p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> *  函数名：uint8_t SPI_WriteReadByte(uint8_t data)</span></span><br><span class="line"><span class="comment"> *  输入参数：pdata -&gt; 要写的一个字节数据</span></span><br><span class="line"><span class="comment"> *  输出参数：无</span></span><br><span class="line"><span class="comment"> *  返回值：读到的数据</span></span><br><span class="line"><span class="comment"> *  函数作用：模拟SPI读写一个字节</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="type">uint8_t</span> <span class="title function_">SPI_WriteReadByte</span><span class="params">(<span class="type">uint8_t</span> data)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">uint8_t</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">uint8_t</span> temp = <span class="number">0</span>;</span><br><span class="line">    <span class="type">uint8_t</span> read_data = <span class="number">0xFF</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>;i&lt;<span class="number">8</span>;i++)</span><br><span class="line">    &#123;</span><br><span class="line">        temp = ((data&amp;<span class="number">0x80</span>)==<span class="number">0x80</span>)? <span class="number">1</span>:<span class="number">0</span>; <span class="comment">// 将data最高位保存到temp；</span></span><br><span class="line">        data = data&lt;&lt;<span class="number">1</span>;                  <span class="comment">// data左移一位，将次高位变为最高位，用于下次取最高位；</span></span><br><span class="line">        read_data = read_data&lt;&lt;<span class="number">1</span>;        <span class="comment">// “腾空” read_data最低位， 8次循环后， read_data将高位在前</span></span><br><span class="line">        </span><br><span class="line">        SPI_CLK(<span class="number">0</span>);        <span class="comment">// 拉低时钟，即空闲时钟为低电平；</span></span><br><span class="line">        SPI_MOSI(temp);    <span class="comment">// 根据temp值，设置MOSI引脚的电平</span></span><br><span class="line">        SPI_Delay();       </span><br><span class="line">        SPI_CLK(<span class="number">1</span>);        <span class="comment">// 拉高时钟，此时从设备会读取MOSI的数据，并写数据到MISO；</span></span><br><span class="line">        SPI_Delay();</span><br><span class="line">        <span class="keyword">if</span>(SPI_MISO()==<span class="number">1</span>)  <span class="comment">// 读取MISO上的数据，保存到当前read_data最低位</span></span><br><span class="line">        &#123;</span><br><span class="line">            read_data = read_data + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    SPI_CLK(<span class="number">0</span>);           <span class="comment">// 最后SPI读写完后，拉低时钟，进入空闲状态；</span></span><br><span class="line">    <span class="keyword">return</span> read_data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第14 - 31行： SPI读和写1 Byte，循环8次，每次发送和接收1 Bit 。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/649464bc.html">通信协议-04-SPI通信</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2022年09月21日 - 17:31</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/649464bc.html" title="通信协议-04-SPI通信">https://sumumm.github.io/post/649464bc.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/" rel="tag"><i class="fa fa-tag"></i> 通信协议</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/fc4e0b5e.html" rel="prev" title="通信协议-06-RS485通信">
                  <i class="fa fa-angle-left"></i> 通信协议-06-RS485通信
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/99876d21.html" rel="next" title="LV01-11-C语言-关键字">
                  LV01-11-C语言-关键字 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">false</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
